<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >

          <el-form-item label="采购单号" prop="orderNo">
            <el-input v-model="formData.orderNo" placeholder="保存后自动生成" disabled />
          </el-form-item>
          <el-form-item label="采购标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入采购标题" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formData.remarks" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item class="mt-20px">
            <el-button :disabled="formLoading" type="primary" @click="submitForm">
              确 定
            </el-button>
          </el-form-item>
        </el-form>


        <!-- 新增采购明细Tab -->
        <el-tabs v-model="activeTab" class="mt-20px" type="border-card">
          <el-tab-pane label="采购明细" name="items">
            <div class="mb-10px">
              <el-button
                type="primary"
                @click="() => openItemDialog()"
              >
                <Icon icon="ep:plus" /> 新增采购明细
              </el-button>
            </div>
            <el-table :data="itemList as any[]" v-loading="itemLoading" style="width: 100%">
              <el-table-column label="物料编码" prop="materialCode" />
              <el-table-column label="物料名称" prop="materialName" />
              <el-table-column label="物料类型" prop="materialType">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.OA_MATERIAL_TYPE" :value="scope.row.materialType" />
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="unitType">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.OA_ASSET_UNIT" :value="scope.row.unitType" />
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity" />
              <el-table-column label="单价" prop="price" />
              <el-table-column label="总价" prop="totalPrice" />
              <el-table-column label="备注" prop="remarks" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="openItemDialog(scope.row, scope.$index)"
                    v-hasPermi="['oa:stock-in:update']"
                  >编辑</el-button>
                  <el-button
                    link
                    type="primary"
                    @click="removeItem(scope.$index)"
                    v-hasPermi="['oa:stock-in:update']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 新增明细弹窗 -->
            <el-dialog v-model="itemDialogVisible" title="新增采购明细" width="500px">
              <el-form :model="itemForm" :rules="itemFormRules" ref="itemFormRef" label-width="80px">
                <el-form-item label="物料" prop="materialId">
                  <el-select v-model="itemForm.materialId" filterable placeholder="请选择物料" @change="handleMaterialChange">
                    <el-option
                      v-for="item in materialList"
                      :key="item.id"
                      :label="item.materialCode + ' - ' + item.materialName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="quantity">
                  <el-input-number v-model="itemForm.quantity" :min="1" />
                </el-form-item>
                <el-form-item label="单价" prop="price">
                  <el-input-number v-model="itemForm.price" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="总价格" prop="totalPrice">
                  <el-input :value="(itemForm.quantity * itemForm.price).toFixed(2)" readonly />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model="itemForm.remarks" placeholder="请输入备注" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="itemDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitItemForm">确定</el-button>
              </template>
            </el-dialog>
          </el-tab-pane>
        </el-tabs>

      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8" >
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>


</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { PurchaseOrderApi, PurchaseOrderVO } from '@/api/oa/purchaseorder'
import { useTagsViewStore } from '@/store/modules/tagsView'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
import { PurchaseOrderItemApi } from '@/api/oa/purchaseorder'
import { MaterialInfoApi, MaterialInfoVO } from '@/api/oa/materialinfo'

defineOptions({ name: 'oaPurchaseOrderCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
          id: undefined,
          userId: undefined,
          userName: undefined,
          orderNo: undefined,
          remarks: undefined,
          status: undefined,
          processInstanceId: undefined,
          creatorName: undefined,
          updaterName: undefined,
          title: '',
})
const formRules = reactive({
      title: [{ required: true, message: '采购标题不能为空', trigger: 'blur' }],
      status: [{ required: true, message: '审批结果不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_purchase_order' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')
const activeTab = ref('items')
const itemList = ref<any[]>([])
const itemLoading = ref(false)
const itemDialogVisible = ref(false)
const itemFormRef = ref()
const itemForm = reactive({
  materialId: undefined,
  materialCode: '',
  materialName: '',
  materialType: undefined,
  unitType: undefined,
  quantity: 1,
  price: 0,
  remarks: undefined as string | undefined
})
const itemFormRules = reactive({
  materialId: [{ required: true, message: '物料不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '单价不能为空', trigger: 'blur' }]
})
const materialList = ref<any[]>([])

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (itemList.value.length === 0) {
    message.error('请至少添加一条采购明细')
    return
  }
  formLoading.value = true
  try {
    // 补全PurchaseOrderVO必填字段，避免undefined
    const req = {
      id: formData.value.id ?? 0,
      userId: formData.value.userId,
      userName: formData.value.userName,
      orderNo: formData.value.orderNo ?? '',
      remarks: formData.value.remarks ?? '',
      status: formData.value.status ?? 0,
      processInstanceId: formData.value.processInstanceId ?? '',
      creatorName: formData.value.creatorName ?? '',
      updaterName: formData.value.updaterName ?? '',
      title: formData.value.title ?? '',
      itemList: itemList.value
    }
    await PurchaseOrderApi.createPurchaseOrder(req)
    message.success('发起成功')
    // 跳转到采购单列表页
    push({ name: 'PurchaseOrder' })
  } finally {
    formLoading.value = false
  }
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      // daysDifference相关逻辑已移除
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

/** 获取物料列表 */
const getMaterialList = async () => {
  const res = await MaterialInfoApi.getMaterialInfoPage({ pageNo: 1, pageSize: 100 })
  materialList.value = res.list || []
}

/** 初始化 */
onMounted(async () => {
  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('采购单主的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
  // 获取采购明细
  if (formData.value.id) {
    // 明细全部前端暂存，无需拉取明细API
  }
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)

const openItemDialog = async (row = null, index = null) => {
  console.log("index:"+index)
  console.log("row:"+JSON.stringify(row))
  await getMaterialList()
  itemDialogVisible.value = true
  if (row && typeof row === 'object') {
    itemForm.materialId = row.materialId
    itemForm.materialCode = row.materialCode
    itemForm.materialName = row.materialName
    itemForm.materialType = row.materialType
    itemForm.unitType = row.unitType
    itemForm.quantity = row.quantity
    itemForm.price = row.price
    itemForm.remarks = (row.remarks ?? undefined) as string | undefined
    (itemForm as any)._editIndex = index
  } else {
    itemForm.materialId = undefined
    itemForm.materialCode = ''
    itemForm.materialName = ''
    itemForm.materialType = undefined
    itemForm.unitType = undefined
    itemForm.quantity = 1
    itemForm.price = 0
    itemForm.remarks = ''
    delete (itemForm as any)._editIndex
  }
}

const handleMaterialChange = (val: number) => {
  const material = (materialList.value as any[]).find(item => item.id === val)
  if (material) {
    itemForm.materialId = material.id
    itemForm.materialCode = material.materialCode
    itemForm.materialName = material.materialName
    itemForm.materialType = material.materialType
    itemForm.unitType = material.unitType
  }
}

const submitItemForm = async () => {
  if (!itemFormRef.value) return
  const valid = await itemFormRef.value.validate()
  if (!valid) return
  const itemData = {
    materialId: itemForm.materialId,
    materialCode: itemForm.materialCode,
    materialName: itemForm.materialName,
    materialType: itemForm.materialType,
    unitType: itemForm.unitType,
    quantity: itemForm.quantity,
    price: itemForm.price,
    totalPrice: (itemForm.quantity * itemForm.price).toFixed(2),
    remarks: itemForm.remarks
  }
  const editIndex: any = (itemForm as any)._editIndex
  console.log(editIndex)
  console.log(itemList.value)
  if (typeof editIndex === 'number') {
    itemList.value.splice(editIndex, 1, itemData)
  } else {
    itemList.value.push(itemData)
  }
  itemDialogVisible.value = false
  // 清空itemForm
  itemForm.materialId = undefined
  itemForm.materialCode = ''
  itemForm.materialName = ''
  itemForm.materialType = undefined
  itemForm.unitType = undefined
  itemForm.quantity = 1
  itemForm.price = 0
  itemForm.remarks = ''
  delete (itemForm as any)._editIndex
  message.success('明细已暂存')
  // 关闭当前 Tab
  delView(unref(currentRoute))
  await push({ name: 'Purchaseorder' })
}

const removeItem = (index) => {
  itemList.value.splice(index, 1)
}

watch(itemDialogVisible, (val) => {
  if (!val) {
    // 弹窗关闭时清空 itemForm
    itemForm.materialId = undefined
    itemForm.materialCode = ''
    itemForm.materialName = ''
    itemForm.materialType = undefined
    itemForm.unitType = undefined
    itemForm.quantity = 1
    itemForm.price = 0
    itemForm.remarks = ''
    delete (itemForm as any)._editIndex
  }
})
</script>
